import { Snake } from './snake.js';
import { Food } from './food.js';

class Game {
  constructor() {
    this.score = 0;
    this.snake = new Snake();
    this.food = new Food();
    this.food.randomizePosition(this.snake.body);
    this.gameOver = false;
    this.isPlaying = false;
    this.canvas = document.getElementById('gameCanvas');
    this.ctx = this.canvas.getContext('2d');
  }

  init() {
    // 初始化游戏
    console.log('游戏初始化中...');
    this.updateScore();
    this.ctx = this.canvas.getContext('2d');
    
    
    // 调整开始按钮位置到画布中央
    const startButton = document.getElementById('startButton');
    startButton.style.position = 'absolute';
    startButton.style.left = '50%';
    startButton.style.top = '50%';
    startButton.style.transform = 'translate(-50%, -50%)';
    
    startButton.addEventListener('click', () => {
      console.log('开始按钮被点击');
      this.startGame();
      startButton.style.display = 'none';
    });
    
    // 创建重新开始按钮
    this.restartButton = document.createElement('button');
    this.restartButton.id = 'restartButton';
    this.restartButton.textContent = '重新开始';
    this.restartButton.style.position = 'absolute';
    this.restartButton.style.left = '50%';
    this.restartButton.style.top = '50%';
    this.restartButton.style.transform = 'translate(-50%, -50%)';
    this.restartButton.style.display = 'none';
    this.restartButton.style.backgroundColor = 'orange';
    this.restartButton.style.color = 'white';
    this.restartButton.style.padding = '10px 20px';
    this.restartButton.style.border = 'none';
    this.restartButton.style.borderRadius = '5px';
    this.restartButton.style.fontSize = '16px';
    this.restartButton.style.cursor = 'pointer';
    document.body.appendChild(this.restartButton);
    
    document.addEventListener('keydown', (e) => {
      switch(e.key) {
        case 'ArrowUp':
          if (this.snake.direction !== 'down') this.snake.direction = 'up';
          break;
        case 'ArrowDown':
          if (this.snake.direction !== 'up') this.snake.direction = 'down';
          break;
        case 'ArrowLeft':
          if (this.snake.direction !== 'right') this.snake.direction = 'left';
          break;
        case 'ArrowRight':
          if (this.snake.direction !== 'left') this.snake.direction = 'right';
          break;
      }
    });
    
    this.restartButton.addEventListener('click', () => {
      this.score = 0;
      this.snake = new Snake();
      this.food.randomizePosition(this.snake.body);
      this.gameOver = false;
      this.isPlaying = false;
      this.updateScore();
      this.restartButton.style.display = 'none';
      this.startGame();
    });
  }

  startGame() {
    if (!this.isPlaying) {
      this.isPlaying = true;
      this.gameLoop();
    }
  }

  updateScore() {
    document.getElementById('score').innerText = `分数: ${this.score}`;
  }

  gameLoop() {
    if (this.gameOver || !this.isPlaying) return;
    
    this.clearCanvas();
    this.draw();
    this.update();
    
    setTimeout(() => {
      requestAnimationFrame(() => this.gameLoop());
    }, this.snake.speed);
  }

  clearCanvas() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  }

  draw() {
    // 绘制高级黑背景
    this.ctx.fillStyle = '#121212';
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    
    // 绘制网格
    this.ctx.strokeStyle = '#1E1E1E';
    this.ctx.lineWidth = 1;
    const gridSize = 30; // 网格尺寸与蛇身一节相同
    
    for (let x = 0; x < this.canvas.width; x += gridSize) {
      this.ctx.beginPath();
      this.ctx.moveTo(x, 0);
      this.ctx.lineTo(x, this.canvas.height);
      this.ctx.stroke();
    }
    
    for (let y = 0; y < this.canvas.height; y += gridSize) {
      this.ctx.beginPath();
      this.ctx.moveTo(0, y);
      this.ctx.lineTo(this.canvas.width, y);
      this.ctx.stroke();
    }
    
    this.snake.draw(this.ctx);
    this.food.draw(this.ctx);
  }

  update() {
    this.snake.move();
    
    if (this.snake.checkCollisionWithFood(this.food)) {
      this.score += this.food.points;
      this.updateScore();
      for (let i = 0; i < this.food.points; i++) {
        this.snake.grow();
      }
      this.food.randomizePosition(this.snake.body);
      return; // 吃到食物后直接返回，避免执行后续碰撞检测
    }
    
    if (this.snake.checkCollisionWithWall() || this.snake.checkCollisionWithSelf()) {
      this.gameOver = true;
      document.getElementById('restartButton').style.display = 'block';
    }
  }
}

export { Game };